package com.qqt.wx.controller;

import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.fastweixin.message.BaseMsg;
import com.fastweixin.message.TextMsg;
import com.fastweixin.message.req.TextReqMsg;
import com.fastweixin.servlet.WeixinControllerSupport;
import com.fastweixin.util.JSONUtil;
import com.qqt.util.WechatConstants;

@RestController
@RequestMapping("/weixin")
public class WeixinController extends WeixinControllerSupport {
        private static final Logger log = LoggerFactory.getLogger(WeixinController.class);
        private static final String TOKEN = "myToken";
        //设置TOKEN，用于绑定微信服务器
        @Override
        protected String getToken() {
            return TOKEN;
        }
        //使用安全模式时设置：APPID
        @Override
        protected String getAppId() {
            return null;
        }
        //使用安全模式时设置：密钥
        @Override
        protected String getAESKey() {
            return null;
        }
        //重写父类方法，处理对应的微信消息
        @Override
        protected BaseMsg handleTextMsg(TextReqMsg msg) {
            String content = msg.getContent();
            log.debug("用户发送到服务器的内容:{}", content);
            return new TextMsg("服务器回复用户消息!");
        }

        @RequestMapping(value="/hello")  
        public String getUserHtml(ModelMap model) {
            //Test HTML view  
            return "example";  
        }
        
        @RequestMapping(value="/auth")  
        public String auth(HttpServletRequest request){
			
			Enumeration<?> e = request.getParameterNames();
			Map<String, String> map = new HashMap<String, String>();
	        while(e.hasMoreElements()){
	            String name = (String)e.nextElement();
	            String value = request.getParameter(name);
	            map.put(name, value);
	        }
	        String r = JSONUtil.toJson(map).toString();
	        log.info(r);

			String body = WechatConstants.get_access_token(map.get("code"));
			log.info(body);
			
            return body;
        }
}